import Router from '@/utils/nav';
import Cookies from '@/utils/storage';
/**
 * @param {url} 路径
 * @param {data} 参数
 * @param {isMethod} 请求类型
 * @param {isForm} 请求头
 */
const Http = {
    request(url, data={}, isMethod, isForm) {
        const method = isMethod ? isMethod : 'GET';
        const header = {
            'content-type':  isForm ? 'application/x-www-form-urlencoded' : 'application/json'
        };
        if( !!Cookies.get('token') ) {
            header['Authorization'] = "Bearer " + Cookies.get('token')
        }
        // 黑名单-移除token
        let blackList = ['/system/user/getByUserPhone', '/puyuTReport/queryById', '/puyuTReport/updateReportNum'];
        blackList.forEach(blackUrl => {
            if( url.includes(blackUrl) ) {
                delete header['Authorization']
            }
        });
        return new Promise((resolve, reject) => {
            if( !data['offShow'] ) {
                uni.showLoading({
                    title: '加载中...'
                });
                delete data['noShow'];
            }
            uni.request({
                url: url, 
                data: data,
                header: header,
                method: method,
                success(res) {
                    uni.hideLoading();
                    if(res.data.code === 401 ) {
                        Router.reLaunch('/pages/authHome/index')
                    }
                    resolve(res.data);
                },
                fail(error) {
                    reject(error);
                    uni.hideLoading();
                }
            });
        });
    },
    uploadFile(url, file) {
        return new Promise((resolve, reject) => {
            uni.showLoading({
                title: '上传中...'
            });
            uni.uploadFile({
                url: url,
                //#ifdef H5
                file: file,
                //#endif
                filePath: file.path,
                name: 'file',
                success(res) {
                    resolve(res.data);
                    uni.hideLoading();
                },
                fail(error) {
                    reject(error);
                    uni.hideLoading();
                }
            });
        });
    }
};
export default Http;